package com.bcnapps.DemoGame;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;

public class Plataformes {
	
	float[] plataformes;
	int nplat;
	Bitmap plataforma;
	float ptx;			//tamany de x de la plataforma
	float pty;
	Resources res;
	
	public Plataformes(Resources resources) {
		res = resources;
		nplat = 1000;
		plataformes = new float[nplat];
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		plataforma = BitmapFactory.decodeResource(GV.Instancies.gametwo.getResources(), R.drawable.cloud, options);
		int tamany = (int)GV.heightpercent(0.15f);
		plataforma = Bitmap.createScaledBitmap(plataforma,tamany,tamany,false);
		ptx = plataforma.getWidth();
		pty = plataforma.getHeight();	
		for(int i=0; i<nplat; i++) plataformes[i] = GV.Screen.metrics.heightPixels*0.8f;
		try {
			load_stage();
		} catch(IOException e) {}
	}
	
	public void load_stage() throws IOException {
		String str="";
		StringBuffer buf = new StringBuffer();			
		InputStream is = res.openRawResource(R.raw.pantallagametwo);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		if (is!=null) {							
			while ((str = reader.readLine()) != null) {	
				buf.append(str + "\n" );
			}				
		}		
		is.close();
		
		str = buf.toString();
		String[] sa = str.split(" ");
		for(int i=0; i<sa.length; i++) {
			plataformes[i] = GV.Screen.metrics.heightPixels*0.8f - ptx*Float.valueOf(sa[i]);
		}
	}
	
	public boolean esta_sobre(float x,float tx, float y, float ty) {
		return y+ty==plataformes[(int)(x/ptx)] || y+ty==plataformes[(int)((x+tx)/ptx)];
	}
	
	public void coloca_sobre(Objecte o) {
		o.y = Math.max(plataformes[(int)(o.x/ptx)], plataformes[(int)((o.x+o.tx)/ptx)])-o.ty;
	}
	
	public boolean colisiona(Rect o) {
		Rect a = new Rect((int)(o.left/ptx)*(int)ptx,(int)(o.left/ptx)*(int)ptx+(int)ptx,(int)plataformes[(int)(o.left/ptx)],(int)plataformes[(int)(o.left/ptx)+(int)ptx]);
		Rect b = new Rect((int)(o.right/ptx)*(int)ptx,(int)(o.right/ptx)*(int)ptx+(int)ptx,(int)plataformes[(int)(o.right/ptx)],(int)plataformes[(int)(o.right/ptx)+(int)ptx]);
		return Rect.intersects(o, a) || Rect.intersects(o, b);
	}
	
	public void draw(Canvas canvas, float dx, float w) {
		for(int i=0; i<w/ptx+1; i++) {
			canvas.drawBitmap(plataforma, i*ptx-dx%ptx, plataformes[i+(int)(dx/ptx)], null);
		}
	}
	
}
